package com.warehouse.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.Action;
import com.warehouse.entity.Admin;
import com.warehouse.service.AdminService;
import com.warehouse.utils.MD5Util;
import com.warehouse.utils.Page;
import com.warehouse.utils.ResultTemplate;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AdminAction {
    private Object obj;
    private AdminService adminService = new AdminService();
    private String phone;
    private String password;

    //登录
    public String login() {
        String newPwd = MD5Util.getMD5Str(password);//MD5加密
        Admin admin = adminService.Login(phone, newPwd);
        if (admin == null) {
            obj = JSONArray.toJSON(new ResultTemplate(500, "登录失败用户名，或者密码输入错误", null));
        } else {
            obj = JSONArray.toJSON(new ResultTemplate(200, "登录成功", admin));
        }
        return Action.SUCCESS;
    }

    private Admin admin;
    //添加管理员
    public String add() {
        admin.setPassword(MD5Util.getMD5Str(admin.getPassword()));
        int add = adminService.add(admin);
        if (add > 0) {
            obj = JSONArray.toJSON(new ResultTemplate(200, "添加成功", null));
        } else {
            obj = JSONArray.toJSON(new ResultTemplate(500, "添加失败", null));
        }
        return Action.SUCCESS;
    }

    //修改管理员
    public String update() {
        int update = adminService.update(admin);
        if (update > 0) {
            obj = JSONArray.toJSON(new ResultTemplate(200, "修改成功", null));
        } else {
            obj = JSONArray.toJSON(new ResultTemplate(500, "修改失败", null));
        }
        return Action.SUCCESS;
    }

    private Integer id;

    //删除管理员
    public String del() {
        int delete = adminService.delete(id);
        if (delete > 0) {
            obj = JSONArray.toJSON(new ResultTemplate(200, "删除成功", null));
        } else {
            obj = JSONArray.toJSON(new ResultTemplate(500, "删除失败", null));
        }
        return Action.SUCCESS;
    }

    //根据id查询内容
    public String byId() {
        Admin admin = adminService.byId(id);
        if (admin != null) {
            obj = JSONArray.toJSON(new ResultTemplate(200, "获取成功", admin));
        } else {
            obj = JSONArray.toJSON(new ResultTemplate(500, "获取失败", null));
        }
        return Action.SUCCESS;
    }

    //分页
    private Integer startPage;

    public String page() {
        Page<Admin> adminPage = adminService.queryPage(startPage, Page.PAGE_SIZE);
        obj = JSONObject.toJSON(adminPage);
        return Action.SUCCESS;
    }

    //模糊查询加分页
    private String name;
    public String byCardNum() {
        Page<Admin> admin = adminService.byCardNum(startPage, Page.PAGE_SIZE, name);
        obj = JSONObject.toJSON(admin);
        return Action.SUCCESS;
    }


}
